<?php
namespace app\api\controller;

use \think\Controller;
use \think\Db;
class Apilogin extends Base
{
    public function getAxes()
    {
        //乐器
        $axes = Db::table('up_axe')
            ->field('axe_id,axe_thumb,axe_name')
            ->select();
        return json(['status' => 200 , 'msg' => $axes]);
    }
    /**
     * 账号密码登录
     * @return bool
     * 参数：账号、密码
     * 返回值：0参数错误，1手机号码错误，2密码格式错误，3没有此用户，4密码错误，5成功
     */
    public  function userLogin(){
        if(!isset($_POST['phone']) || !isset($_POST['pass'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $pass = $_POST['pass'];
        if(preg_match("/^1[123456789]\d{9}$/", $phone)){
            if(empty($pass) || !isset($pass)){
                return json_encode(['status'=>2,'msg'=>'请填写正确的密码']);
            }else{
                $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
                if(empty($username)){
                    return json_encode(['status'=>3,'msg'=>'没有此用户']);
                }else{
                    if($username['user_password'] != md5($pass)){
                        return json_encode(['status'=>4,'msg'=>'密码错误']);
                    }else{
                        if($username['user_status'] != 1){
                            return json_encode(['status'=>4,'msg'=>'此账户已被冻结']);
                        }
                        //更新token
                        $token = md5(date('YmdHis') . rand(100000,999999));
                        Db::table('up_u_user')->where('user_phone',$phone)
                            ->update(['user_token'=>$token]);
                        $username['user_token'] = $token;
                        return json_encode(['status'=>200,'msg'=>$username]);
                    }
                }
            }
        }else{
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
    }

    /**
     * 手机登录或注册时发送的验证码
     * @return bool
     * 参数：phone bind_type(1是登录和更换手机号(第一步) 2是注册和更换手机号(第二步) 3是忘记密码（和修改密码）  4是第三方登录时的绑定手机号)
     * 返回值：0参数错误，1手机格式错误，21登录无此号，22注册有此号，3验证码发送失败，4返回md5加密验证码
     */
    public  function getPhoneCode(){
        if(!isset($_POST['phone']) || !isset($_POST['type'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $type = $_POST['type'];
        if(!preg_match("/^1[123456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username) && $type==1){
            return json_encode(['status'=>21,'msg'=>'没有此手机号码用户']);
        }
        if(empty($username) && $type==3){
            return json_encode(['status'=>21,'msg'=>'没有此手机号码用户']);
        }
        if(!empty($username) && $type==2){
            return json_encode(['status'=>22,'msg'=>'已经有此手机号码用户']);
        }
        if(!empty($username) && $type == 4) {//第三方登录时绑定手机号
            if($_POST['bind_type'] == 1) {
                $field = '_wx_';
            }else if($_POST['bind_type'] == 2) {
                $field = '_qq_';
            }else if($_POST['bind_type'] == 3) {
                $field = '_wb_';
            }else {
                $field = '_ios_';
            }
            if($username["user{$field}token"]) {
                return json(['status' => 0, 'msg' => '此号码已被绑定']);
            }
        }
        $num = GetRandCode();//6位数验证码
//        $num = 123456;//6位数验证码
        $templateid = config('yzx.templateid');
        $sendres = YzxSms($templateid,$num,$phone,'');
        if($sendres['code'] != '000000'){
            return json_encode(['status'=>3,'msg'=>$sendres['msg']]);
        }else {
            //=============================
            $isset = Db::table('up_phonecode')->where('phone', $phone)->find();
            if ($isset) {
                $res = Db::table('up_phonecode')->where('phone', $phone)->update(['code' => md5($num), 'time2' => time(), 'status' => 0]);
            } else {
                $res = Db::table('up_phonecode')->insert(['phone' => $phone, 'code' => md5($num), 'time2' => time()]);
            }
            if (!$res) {
                return json_encode(['status' => 31, 'msg' => '数据库操作失败']);
            }
            //===============================================
            return json_encode(['status' => 200, 'msg' => md5($num)]);
        }
    }
    /**
     * 手机号码登录
     * @return bool
     * 参数：phone，code
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，4成功
     */

    public  function phoneLogin(){
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];

        if(!preg_match("/^1[123456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 600){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json_encode(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        if($username['user_status'] != 1){
            return json_encode(['status'=>4,'msg'=>'此账户已被冻结']);
        }
        Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
        $token = md5(date('YmdHis') . rand(100000,999999));
        Db::table('up_u_user')->where('user_phone',$phone)
            ->update(['user_token'=>$token]);
        $username['user_token'] = $token;
        return json_encode(['status'=>200,'msg'=>$username]);
    }

    /**
     * 注册
     * @return bool
     * 参数：phone,code,password
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，4有其他未填项，5插入登录表失败，200成功
     */

    public  function userReg(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        if(!isset($_POST['password'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $pass = $_POST['password'];
        $pass2 = $_POST['password2'];
        if(!preg_match("/^1[123456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json_encode(['status'=>3,'msg'=>'已经有此手机号码用户']);
        }
        if($pass=='' || $code==''){
            return json_encode(['status'=>4,'msg'=>'有未填项，请检查']);
        }
        if($pass != $pass2){
            return json_encode(['status'=>4,'msg'=>'密码输入不一致']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 600){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $data = array();
        $data['user_password'] = md5($pass);
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_update_time'] = date('Y-m-d H:i:s');
        $data['user_last_login_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        $data['user_phone'] = $phone;
        $data['user_username'] = '用户'. substr($phone,-4,4);

        $id = Db::name('u_user')->insertGetId($data);
        if($id){
            $user = Db::table('up_u_user')
                ->where('user_id',$id)
                ->find();
            //乐器
            $axes = Db::table('up_axe')
                ->field('axe_id,axe_thumb,axe_name')
                ->select();
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);

            return json_encode(['status'=>200,'msg'=>$user,'axes'=>$axes]);
        }else{
            return json_encode(['status'=>5,'msg'=>'生成数据失败,请刷新重试']);
        }
    }

    /**
     * 选择喜欢的乐器
     * @return string
     */
    public  function userLikeAxe(){
        $user_id = $_POST['user_id'];
        $axe_id = $_POST['like']; //喜欢的乐器id，其他传9999
        $buy = $_POST['buy']; //0代表未选  喜欢是1  其他直接传输入的字符串
        $other = $_POST['other']; //0代表未选  喜欢是1  其他直接传输入的字符串
        //=============================================
        $res = Db::table('up_u_user')->where('user_id',$user_id)->update([
            'user_like_axe' => trim($axe_id,','),
            'user_buy_axe' => trim($buy,','),
            'user_other_axe' => $other,
            'user_update_time' => date('Y-m-d H:i:s')
        ]);
        //=============================================================
        if($res){
            $user = Db::table('up_u_user')
                ->where('user_id',$user_id)
                ->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>5,'msg'=>'生成数据失败,请刷新重试']);
        }
    }

    /**
     * 忘记密码（修改密码）
     * @return bool
     * phone  手机号
     * code  验证码
     */
    public function forgetPass()
    {
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        $pass = $_POST['password'];
        $pass2 = $_POST['password2'];
        if($phone == '') {
            return json(['status' => 0, 'msg' => '请输入手机号码']);
        }
        if($code == '') {
            return json(['status' => 0, 'msg' => '请输入验证码']);
        }
        if(!preg_match("/^1[123456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($userInfo)) {
            return json(['status' => 0, 'msg' => '该账号不存在']);
        }
        if($pass != $pass2){
            return json_encode(['status'=>4,'msg'=>'密码输入不一致']);
        }
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 600) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }

        if($userInfo['user_status'] == 2) {
            return json(['status' => 0, ' msg' => '该账号已被冻结']);
        }
        if($userInfo['user_status'] == 3) {
            return json(['status' => 0, ' msg' => '该账号已被删除，请联系管理员']);
        }
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $update = [
            'user_token' => $token,
            'user_password' => md5($pass),
            'user_update_time' => date('Y-m-d H:i:s')
        ];
        $res2 = Db::table('up_u_user')
            ->where('user_phone', $phone)
            ->update($update);
        if($res2){
            Db::table('up_phonecode')->where('id', $res['id'])->update(['status' => 1]);
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '修改密码失败']);
        }
    }

    /**
     * 登录后的修改密码（直接输入原密码和新密码）第一步
     * password  密码
     * user_id  用户ID
     */
    public function updatePassFirst()
    {
        $pass = $_POST['password'];
        $user_id = $_POST['user_id'];
        $old = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->value('user_password');
        if($old) {
            if($old != md5($pass)){
                return json(['status' => 0, 'msg' => '密码错误！']);
            }else{
                return json(['status' => 200, 'msg' => 'OK']);
            }
        }else{
            return json(['status' => 0, 'msg' => '手机号码有误，请重新登录']);
        }
    }
    /**
     * 登录后的修改密码（直接输入原密码和新密码）第二步
     * password  密码
     * user_id  用户ID
     */
    public function updatePassSecend()
    {
        $pass = $_POST['newpassword'];
        $user_id = $_POST['user_id'];
        $update = [
            'user_password' => md5($pass),
            'user_update_time' => date('Y-m-d H:i:s')
        ];
        $res = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->update($update);
        if($res) {
            return json(['status' => 200, 'msg' => 'OK']);
        }else{
            return json(['status' => 0, 'msg' => '密码修改失败，请刷新重试']);
        }
    }
    /**
     * 第三方登录/注册
     * @return \think\response\Json
     * thirdToken   微信token
     */
    public function thirdLogin(){
        $user_wx_token = input('thirdToken');

        $isHave = Db::table('up_u_user')
            ->where('user_wx_token|user_qq_token|user_wb_token|user_ios_id', $user_wx_token)
            ->find();

        if($isHave) { // 如果登录过
            if($isHave['user_status'] != 1) {
                return json(['status' => 0, 'msg' => '该账号已被冻结']);
            }
            if($isHave['user_status'] == 3) {
                return json(['status' => 0, 'msg' => '该账号已被删除']);
            }
            $token = md5(date('YmdHis') . rand(100000, 999999));
            $data['user_token'] = $token;
            $data['user_update_time'] = date('Y-m-d H:i:s');
            $res = Db::table('up_u_user')->where('user_wx_token|user_qq_token|user_wb_token|user_ios_id', $user_wx_token)->update($data);
            if($res){
                $info = Db::table('up_u_user')->where('user_wx_token|user_qq_token|user_wb_token|user_ios_id', $user_wx_token)->find();
                return json(['status' => 200, 'msg' => $info]);
            }else{
                return json(['status' => 0, 'msg' => '登录失败，请刷新重试']);
            }
        }else{
            return json(['status' => 300, 'msg' => '第一次登录，去绑定手机号']);
        }
    }

    /**
     * 绑定手机号
     * @return \think\response\Json
     * phone        手机号
     * code         验证码
     * thirdToken   微信token
     * thirdName    微信昵称
     * thirdImg     微信头像
     */
    public function binding(){
        $phone = trim($_POST['phone'], ' ');
        $code = trim($_POST['code'], ' ');
        $user_wx_token = $_POST['thirdToken'];
        $type = $_POST['bind_type'];
        if($type != 4){
            $user_wx_nickname = input('thirdName');
            $user_wx_image = input('thirdImg');
        }
        if($type == 1) {
            $field = '_wx_';
        }else if($type == 2) {
            $field = '_qq_';
        }else if($type == 3) {
            $field = '_wb_';
        }else {
            $field = '_ios_';
        }
        if($phone == '' || $code == '') {
            return json(['status' => 0, 'msg' => '有未填项，请检查']);
        }
        //验证手机号
        if(!preg_match("/^1[123456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        //验证验证码
        $res = Db::table('up_phonecode')->where('phone', $phone)->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 600) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        $isHave = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if($isHave){
            if($isHave['user_status'] == 2){
                return json(['status' => 0, 'msg' => '该账号已被冻结']);
            }
            if($isHave['user_status'] == 3){
                return json(['status' => 0, 'msg' => '该账号已被删除']);
            }
            if($isHave["user{$field}token"]){
                return json(['status' => 0, 'msg' => '该手机号已被绑定！']);
            }
        }

        $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_token'] = $token;
        $data["user{$field}token"] = $user_wx_token;
        if($type != 4){
            $data["user{$field}nickname"] = $user_wx_nickname;
            $data["user{$field}image"] = $user_wx_image;
        }
        $data['user_update_time'] = date('Y-m-d H:i:s');
        $data['user_last_login_time'] = date('Y-m-d H:i:s');
        Db::startTrans();
        try{
            if($isHave){ // 登录
                if($type != 4) {
                    if (empty($isHave['user_username'])) {
                        $data['user_username'] = $user_wx_nickname;
                    }
                    if (empty($isHave['user_image'])) {
                        $data['user_image'] = $user_wx_image;
                    }
                }else{
                    if (empty($isHave['user_username'])) {
                        $data['user_username'] = '用户'. substr($phone,-4,4);
                    }
                }
                Db::table('up_u_user')->where('user_phone', $phone)->update($data);
            }else{ // 注册&登录
                $data['user_phone'] = $phone;
                $data['user_time'] = date('Y-m-d H:i:s');
                if($type != 4) {
                    $data['user_username'] = $user_wx_nickname;
                    $data['user_image'] = $user_wx_image;
                }else{
                    $data['user_username'] = '用户'. substr($phone,-4,4);
                }
                Db::table('up_u_user')->insert($data);
            }
            // 修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            Db::commit();
            $res = 1;
        }catch(\Exception $e){
            Db::rollback();
            $res = 2;
        }

        if($res == 1){
            //乐器
            $axes = Db::table('up_axe')
                ->field('axe_id,axe_thumb,axe_name')
                ->select();
            //注册成功后自动登录
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            return json(['status' => 200, 'msg' => $userInfo, 'axes' => $axes]);
        }else{
            return json(['status' => 0, 'msg' => '登录失败']);
        }
    }
    /**
     * 登陆后绑定第三方
     * @return \think\response\Json
     * thirdToken   微信token
     * thirdName    微信昵称
     * thirdImg     微信头像
     */
    public function bindingAfterLogin(){
        $user_id = $_POST['user_id'];
        $user_wx_token = $_POST['thirdToken'];
        $type = $_POST['bind_type'];
        if($type != 4){
            $user_wx_nickname = input('thirdName');
            $user_wx_image = input('thirdImg');
        }
        if($type == 1) {
            $field = '_wx_';
        }else if($type == 2) {
            $field = '_qq_';
        }else if($type == 3) {
            $field = '_wb_';
        }else {
            $field = '_ios_';
        }

        $isHave = Db::table('up_u_user')->where('user_id', $user_id)->find();
        $data["user{$field}token"] = $user_wx_token;
        if($type != 4){
            $data["user{$field}nickname"] = $user_wx_nickname;
            $data["user{$field}image"] = $user_wx_image;
        }
        $data['user_update_time'] = date('Y-m-d H:i:s');
        if($type != 4) {
            if (empty($isHave['user_image'])) {
                $data['user_image'] = $user_wx_image;
            }
        }
        $res = Db::table('up_u_user')->where('user_id', $user_id)->update($data);
        if($res){
            //注册成功后自动登录
            $userInfo = Db::table('up_u_user')->where('user_id', $user_id)->find();
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '绑定失败']);
        }
    }

    /**
     * 第三方登录第一次绑定时候设置的密码（待定）
     * @return \think\response\Json
     */
    public function setPassForLogin()
    {
        $pass = $_POST['pass'];
        $phone = $_POST['phone'];
        $data['user_password'] = md5($pass);
        $data['user_time'] = date('Y-m-d H:i:s');
        $res = Db::table('up_u_user')->where('user_phone', $phone)->update($data);
        if($res){
            //注册成功后自动登录
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '更改失败']);
        }
    }
//-----------------------------------------------------------------------------------------------------------

    /**
     * 修改手机号第一步
     * @return \think\response\Json
     * phone  用户手机号
     * code  验证码
     */
    public function changePhoneF(){
        $phone = input('phone');
        $code = input('code');

        if($code == '') {
            return json(['status' => 0, 'msg' => '请输入验证码']);
        }
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 600) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        $result = Db::table('up_phonecode')->where('id', $res['id'])->update(['status' => 1]);
        if($result){
            return json(['status' => 200, 'msg' => 'OK']);
        }else{
            return json(['status' => 0, 'msg' => '未知错误，再点一次']);
        }
    }

    /**
     * 修改手机号第二步
     * @return \think\response\Json
     * user_id  用户ID
     * phone  用户手机号
     * code  验证码
     */
    public function changePhoneS(){
        $phone = input('newphone');
        $code = input('code');
        $user_id = input('user_id');

        if($phone == '') {
            return json(['status' => 0, 'msg' => '请输入手机号码']);
        }

        if($code == '') {
            return json(['status' => 0, 'msg' => '请输入验证码']);
        }

        if(!preg_match("/^1[34578]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }

        $info = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if($info){
            return json(['status' => 0, 'msg' => '该手机号已注册']);
        }

        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 600) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }

        $result = Db::table('up_u_user')->where('user_id', $user_id)->update(
            [
                'user_phone' => $phone,
                'user_update_time' => date('Y-m-d H:i:s')
            ]);

        if($result){
            $user = Db::table('up_u_user')->where('user_id', $user_id)->find();
            Db::table('up_phonecode')->where('id', $res['id'])->update(['status' => 1]);
            return json(['status' => 200, 'msg' => $user]);
        }else{
            return json(['status' => 0, 'msg' => '修改失败']);
        }
    }


}